package com.citms.hander;

import javax.servlet.http.HttpServletRequest;

import com.citms.exception.CloudException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.citms.common.CodeMsg;
import com.citms.common.ResultInfo;
import com.citms.exception.BussinessException;

import lombok.extern.slf4j.Slf4j;

/*
 *
 * 全局异常处理类
 * 
 * @author denghq
 * @date 2018/10/29
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 全局异常处理
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Object allExceptionHandler(HttpServletRequest request, Exception exception) {
        //
        //

        //json结果处理
        //异常处理顺序 ：1.业务异常(参数验证异常，业务异常等)
        //               2.重复插入异常
        //               3.404 异常
        //               4.权限异常
       // 				 5.500异常	
        if (exception instanceof BussinessException){
            BussinessException ex = (BussinessException)exception;
            return ResultInfo.error(ex.getCodeMsg());
         } else if (exception instanceof DuplicateKeyException){
            return ResultInfo.error(CodeMsg.INSER_ERROR);
        }  else if (exception instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            return ResultInfo.error(CodeMsg.SERVER_RESOURCES_UNAVAILABLE);
        }else if (exception instanceof CloudException) {
            return ((CloudException) exception).getRes();
        } else {
        	exception.printStackTrace();
        	log.error(exception.getMessage(),exception);
            return ResultInfo.error(CodeMsg.OTHER_ERROR);
        }
    }

}
